package qinggui.mlz.console.controller.tag;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import qinggui.mlz.module.tag.entity.Tag;
import qinggui.mlz.module.tag.service.TagService;
import qinggui.mlz.module.utils.Response;

import java.util.List;

/**
 * <p>
 * 标签表 前端控制器
 * </p>
 *
 * @author qinggui
 * @since 2025-08-10
 */
@RestController
@Slf4j
public class TagController {

    @Autowired
    private TagService tagService;

    /**
     * 1. 获取列表标签
     *
     * @return Response
     */
    @RequestMapping("/tag/list")
    public Response getAll() {
        List<Tag> allList = null;
        try {
            allList = tagService.getAllList();
        } catch (Exception e) {
            log.error("获取列表标签失败", e);
            throw new RuntimeException(e);
        }
        if (allList == null) {
            return null;
        }
        return new Response<>(1001, allList);
    }

    /**
     * 2. 添加标签
     *
     * @param name 标签名称
     * @return Response
     */
    @RequestMapping("/tag/add")
    public Response add(@RequestParam String name) {
        if (name == null || name.isEmpty()) {
            return new Response<>(4004, "名字不能为空");
        }
        String save = null;
        try {
            save = tagService.edit(null, name);
            return new Response<>(1001, save);
        } catch (Exception e) {
            log.error("添加标签失败：", e);
            return new Response<>(4004, "添加失败");
        }
    }

    /**
     * 3. 更新标签
     *
     * @param id 标签id
     * @return Response
     */
    @RequestMapping("/tag/update")
    public Response update(@RequestParam Long id, @RequestParam String name) {
        if (name == null || name.isEmpty()) {
            return new Response<>(4004, "名字不能为空");
        }
        try {
            String isUpdate = tagService.edit(id, name);
            return new Response<>(1001, isUpdate);
        } catch (Exception e) {
            log.error("更新标签失败", e);
            return new Response<>(4004, "更新失败");
        }
    }

    /**
     * 4. 删除标签
     *
     * @param id 标签id
     * @return Response
     */
    @RequestMapping("/tag/delete")
    public Response delete(@RequestParam Long id) {
        try {
            String isDeleted = tagService.delete(id);
            return new Response<>(1001, isDeleted);
        } catch (Exception e) {
            log.error("删除标签失败", e);
            return new Response<>(4004, "删除失败");
        }
    }
}
